<template>
  <!-- 对话框 -->
  <el-dialog
    model-value="loginDialogVisible"
    width="50%"
    @close="handleClose"
  >
    <div class="content">
      <div class="content-top">
        <div class="content-top-left">
          <img src="@/assets/images/logincover.jpeg" alt="登录封面">
        </div>
        <div class="content-top-right">
          <div class="content-top-right-title">账号登录 | 短信登录</div>
          <!-- 表单 -->
          <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item prop="acc">
              <el-input v-model.number="ruleForm.acc" :clearable="true">
                <template #prepend>
                  账号
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="pass">
              <el-input v-model="ruleForm.pass" type="password" autocomplete="off" :clearable="true">
                <template #prepend>
                  密码
                </template>
              </el-input>
            </el-form-item>
            <el-form-item style="text-align: center">
              <el-button
                style="margin: auto"
                type="primary"
                @click="submitForm(ruleFormRef)"
              >
                登录/注册
              </el-button>
            </el-form-item>
          </el-form>
        </div>     
      </div>
      <div class="content-bottom">
        注册登录账号表示你同意相关 用户协议 与 隐私政策
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, defineEmits } from "vue";
import type { FormInstance } from "element-plus";
import {useRouter} from 'vue-router'
import {loginApi} from '@/api/login.js'
import {userApi} from '@/api/user.js'
import { ElMessage } from 'element-plus'

//### 数据定义 ###
//声明事件
const emit = defineEmits(['close-dialog'])

// 数据校验
const ruleFormRef = ref<FormInstance>();

const checkAcc = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("请输入账号名"));
  }
  setTimeout(() => {
    //后续改为正则匹配检查账号是否符合规范，要和后端统一

    callback();
    // if (value < 18) {
    //   callback(new Error("Age must be greater than 18"));
    // } else {
    //   callback();
    // }
  }, 1000);
};

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    //一样的检查密码的格式
    // if (ruleForm.checkPass !== "") {
    //   if (!ruleFormRef.value) return;
    //   ruleFormRef.value.validateField("checkPass");
    // }
    callback();
  }
};

const ruleForm = reactive({
  pass: "",
  acc: "",
});

const rules = reactive<FormRules<typeof ruleForm>>({
  pass: [{ validator: validatePass, trigger: "blur" }],
  acc: [{ validator: checkAcc, trigger: "blur" }],
});

//其余数据
const router = useRouter();

//### 方法定义 ###
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        const data = await loginApi.login({
          username: ruleForm.acc,
          password: ruleForm.pass,
          loginType: "member_type"
        })

        if(data.code === 200) {
          window.localStorage.setItem("ten-seek-jwt", data.data.token);
          const authoritiesJsonString = JSON.stringify(data.data.authorities);
          window.localStorage.setItem("ten-seek-privilege", authoritiesJsonString);
          window.localStorage.setItem("ten-seek-nickname", ruleForm.acc); //存储昵称
          const result = await userApi.getTheAvatarThroughTheUsername({username : ruleForm.acc});
          console.log("看看获取头像地址", result)
          if(result.code === 200) {
            window.localStorage.setItem("ten-seek-avatar", result.data.avatar);
          }
          handleClose();  //关闭对应弹窗

          router.push({
            name: 'collect'
          })
        }else {
          ElMessage.error('你输入的密码或账号有误');
        }
      }catch (e) {
        ElMessage.error('你输入的密码或账号有误，出现了异常');
      }
    } else {
      console.log("校验失败");
    }
  });
};

//关闭操作
const handleClose = () => {
  console.log("关闭");
  emit('close-dialog'); //触发事件
};
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;

  .content-top {
    display: flex;
    flex-direction: row; /* 保持主轴为水平方向 */
    justify-content: space-between; /* 使子项在主轴上两端分布 */
    align-items: center;
    margin-top: 10px;

    .content-top-left {
      flex: 5;
      margin-right: 10px;

      img {
        width: 100%;
      }
    }

    .content-top-right {
      flex: 5;
      display: flex;
      flex-direction: column;
      align-items: center;

      .content-top-right-title {
        margin-bottom: 10px;
        font-size: 18px;
      }
    }
  }

  .content-bottom {
    text-align: center;
    margin-top: 30px;
  }
}
</style>
